package com.ruoyi.system.recovery.service.impl;

import java.util.List;
import java.util.Arrays;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.recovery.domain.RecoverySaleMoney;
import com.ruoyi.system.recovery.mapper.RecoverySaleMoneyMapper;
import com.ruoyi.system.recovery.service.IRecoverySaleMoneyService;
import lombok.extern.slf4j.Slf4j;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

/**
 * 历史销售价格Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-06-09
 */
@Slf4j
@Service
public class RecoverySaleMoneyServiceImpl extends ServiceImpl<RecoverySaleMoneyMapper, RecoverySaleMoney> implements IRecoverySaleMoneyService {

    /**
     * 查询历史销售价格
     * 
     * @param id 历史销售价格主键
     * @return 历史销售价格
     */
    @Override
    public RecoverySaleMoney selectRecoverySaleMoneyById(Long id) {
        return super.getById(id);
    }

    /**
     * 查询历史销售价格列表
     * 
     * @param recoverySaleMoney 历史销售价格
     * @return 历史销售价格
     */
    @Override
    public List<RecoverySaleMoney> selectRecoverySaleMoneyList(RecoverySaleMoney recoverySaleMoney) {
        return baseMapper.selectRecoverySaleMoneyList(recoverySaleMoney);
    }

    /**
     * 新增历史销售价格
     * 
     * @param recoverySaleMoney 历史销售价格
     * @return 结果
     */
    @Override
    public boolean insertRecoverySaleMoney(RecoverySaleMoney recoverySaleMoney) {
        // 查询最近的价格
        RecoverySaleMoney rsm = super.getOne(Wrappers.lambdaQuery(RecoverySaleMoney.class)
                .eq(RecoverySaleMoney::getRecoveryInfoId, recoverySaleMoney.getRecoveryInfoId())
                .orderByDesc(RecoverySaleMoney::getCreateTime)
                .last("limit 1")
        );
        if(rsm == null){
            recoverySaleMoney.setOldSaleMoney(recoverySaleMoney.getSaleMoney());
        }else{
            recoverySaleMoney.setOldSaleMoney(rsm.getSaleMoney());
        }

        recoverySaleMoney.setUserId(SecurityUtils.getUserId());
        return super.save(recoverySaleMoney);
    }

    /**
     * 修改历史销售价格
     * 
     * @param recoverySaleMoney 历史销售价格
     * @return 结果
     */
    @Override
    public boolean updateRecoverySaleMoney(RecoverySaleMoney recoverySaleMoney) {
        return super.updateById(recoverySaleMoney);
    }

    /**
     * 批量删除历史销售价格
     * 
     * @param ids 需要删除的历史销售价格主键
     * @return 结果
     */
    @Override
    public boolean deleteRecoverySaleMoneyByIds(Long[] ids) {
        return super.removeByIds(Arrays.asList(ids));
    }

    /**
     * 删除历史销售价格信息
     * 
     * @param id 历史销售价格主键
     * @return 结果
     */
    @Override
    public boolean deleteRecoverySaleMoneyById(Long id) {
        return super.removeById(id);
    }

}
